package httpbot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.IOUtils;

import com.google.common.base.Preconditions;

public class HttpRequests implements IRequests{

	@Override
	public String getPageSource(String title) {
		Preconditions.checkNotNull(title);
		Preconditions.checkArgument(title.length() > 0, "Paramater must have a length");
		RequestBuilder builder = new RequestBuilder();
		builder.setAction("query").setProp("revisions").setRvprop("content").setFormat("json").setTitles(title);
		
		BufferedReader reader = null;
		StringBuilder stringBuilder = new StringBuilder(1000);
		try{
			URL url = new URL(builder.create());
			reader = new BufferedReader(new InputStreamReader(url.openStream()));
			String line = null;
			while ((line = reader.readLine()) != null){
				stringBuilder.append(line);
				stringBuilder.append("\n");
			}
		} 
		catch (MalformedURLException e){
			e.printStackTrace();
		} 
		catch (IOException e){
			e.printStackTrace();
		}
		finally{
			IOUtils.closeQuietly(reader);
		}
		
		return stringBuilder.toString();
	}
}
